﻿using System;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using System.Security.Cryptography;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.DAL;
using Matrix.MaKaYunShang.Model.Dto;

namespace Matrix.MaKaYunShang.BLL
{
    public partial class CouponBLL : BaseBLL<CouponBLL>
    {
        #region 默认方法
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Coupon model)
        {
            return CouponDAL.Instance.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Coupon model)
        {
            return CouponDAL.Instance.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {
            return CouponDAL.Instance.Delete(Id);
        }
        /// <summary>
        /// 批量删除一批数据
        /// </summary>
        public bool DeleteList(string Idlist)
        {
            return CouponDAL.Instance.DeleteList(Idlist);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Coupon GetModel(int Id)
        {
            var ds = CouponDAL.Instance.GetModel(Id);
            return ds == null ? null : ServicesHelper.DataSetToIList<Coupon>(ds).ToList()[0];
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Coupon> GetModelList(string strWhere = null)
        {
            var ds = CouponDAL.Instance.GetList(strWhere);
            return ServicesHelper.DataSetToIList<Coupon>(ds).ToList();
        }
        #endregion

        #region 扩展方法

        /// <summary>
        /// 获取用户优惠券列表
        /// </summary>
        /// <param name="consumerId">消费者ID</param>
        /// <param name="isChooseUsable">是否只提取可用优惠券</param>
        /// <param name="commodityLibList">店铺商品Lib集合（可选）</param>
        /// <returns></returns>
        public List<CouponDto> GetCouponListOfCousumer(int consumerId, bool isChooseUsable, List<CommodityLib> commodityLibList = null )
        {
            var lsCouponInfo = CouponDAL.Instance.GetCouponListOfCousumer(consumerId, isChooseUsable);
            if (lsCouponInfo == null || lsCouponInfo.Count == 0)
                return null;

            var arrCouponIds = lsCouponInfo.Select(p => p.Id).Distinct();
            var couponIds = arrCouponIds as int[] ?? arrCouponIds.ToArray();
            if (!couponIds.Any())
            {
                return null;
            }
            var strCouponIds = string.Join(",", couponIds);
            var lsCouponBrand = CouponBrandBLL.Instance.GetListByCouponIds(strCouponIds);
            var lsCouponCommodityLib = CouponCommodityLibDAL.Instance.GetListByCouponIds(strCouponIds);
            var lsCouponCommodityCategory = CouponCommodityCategoryDAL.Instance.GetListByCouponIds(strCouponIds);
            
            var arrCommodityBrands = new int[] {};
            var arrCommodityCategoryIds = new int[] {};
            var arrCommodityLibIds = new int[] {};

            if (commodityLibList != null && commodityLibList.Count > 0)
            {
                var lsBrands = commodityLibList.Select(p => p.BrandId);
                arrCommodityBrands = lsBrands as int[] ?? lsBrands.ToArray();

                var lsCategoryIds = commodityLibList.Select(p => p.CateId);
                arrCommodityCategoryIds = lsCategoryIds as int[] ?? lsCategoryIds.ToArray();
            
                var lsCommodityLibIds = commodityLibList.Select(p => p.Id);
                arrCommodityLibIds = lsCommodityLibIds as int[] ?? lsCommodityLibIds.ToArray();
            }
            

            var lsCouponDto = new List<CouponDto>();
            foreach (var couponInfo in lsCouponInfo)
            {
                var couponDto = new CouponDto {CouponInfo = couponInfo};

                if (lsCouponBrand != null && lsCouponBrand.Count > 0)
                {
                    couponDto.CouponBrandLimitList = lsCouponBrand.FindAll(p => p.CouponId == couponInfo.Id);
                    if (arrCommodityBrands.Length > 0 && couponDto.CouponBrandLimitList != null &&
                        couponDto.CouponBrandLimitList.Count > 0)
                    {
                        var checkListBrand = from p in couponDto.CouponBrandLimitList
                            where (arrCommodityBrands.Contains(p.CommodityBrandId))
                            select p;
                        if (!checkListBrand.Any())
                        {
                            continue;
                        }
                    }
                }

                if (lsCouponCommodityLib != null && lsCouponCommodityLib.Count > 0)
                {
                    couponDto.CouponCommodityLibLimitList =
                        lsCouponCommodityLib.FindAll(p => p.CouponId == couponInfo.Id);
                    if (arrCommodityLibIds.Length > 0 && couponDto.CouponCommodityLibLimitList != null &&
                        couponDto.CouponCommodityLibLimitList.Count > 0)
                    {
                        var checkListCommodityLib = from p in couponDto.CouponCommodityLibLimitList
                            where (arrCommodityLibIds.Contains(p.CommodityLibId))
                            select p;
                        if (!checkListCommodityLib.Any())
                        {
                            continue;
                        }
                    }
                }

                if (lsCouponCommodityCategory != null && lsCouponCommodityCategory.Count > 0)
                {
                    couponDto.CouponCommodityCategoryLimitList =
                        lsCouponCommodityCategory.FindAll(p => p.CouponId == couponInfo.Id);
                    if (arrCommodityCategoryIds.Length > 0 && couponDto.CouponCommodityCategoryLimitList != null &&
                        couponDto.CouponCommodityCategoryLimitList.Count > 0)
                    {
                        var checkListCommodityCategory = from p in couponDto.CouponCommodityCategoryLimitList
                            where (arrCommodityCategoryIds.Contains(p.CommodityCategoryId))
                            select p;
                        if (!checkListCommodityCategory.Any())
                        {
                            continue;
                        }
                    }
                }

                lsCouponDto.Add(couponDto);
            }

            return lsCouponDto;
        }

        /// <summary>
        ///     获得分页数据列表
        /// </summary>
        public TableDataViewDto<ViewCouponDto> GetPagingList(int draw, int pageIndex, int pageSize, string searchKeyWord, string colOrder)
        {
            try
            {
                int totalCount = 0;
                List<ViewCouponDto> list = CouponDAL.Instance.GetPagingList(pageIndex, pageSize, searchKeyWord, colOrder, ref totalCount);
                list.ForEach(a =>
                {
                    a.Action =
                        "<a class='btn btn-warning' href='javascript:;' onclick=updateData(" + a.Id + ");>修改</a> " +
                        "<a class='btn btn-danger' href='javascript:;' onclick=deleteData(" + a.Id + ");>删除</a>";
                    a.StartTimeStr = a.StartTime.ToString();
                    a.EndTimeStr = a.EndTime.ToString();
                }
                    );
                var returnDataList = new TableDataViewDto<ViewCouponDto>
                               {
                                   data = list,
                                   draw = draw,
                                   recordsFiltered = totalCount,
                                   recordsTotal = totalCount
                               };

                return returnDataList;
            }
            catch (Exception ex)
            {
                _fileLog.Error(" GetPagingList | Exception: " + ex);
                return null;
            }
        }

        /// <summary>
        /// 获取用户优惠券信息
        /// </summary>
        /// <param name="consumerCouponId">消费者优惠券ID</param>
        /// <returns></returns>
        public CouponDto GetCouponInfoByConsumerCouponId(int consumerCouponId)
        {
            var couponInfo = CouponDAL.Instance.GetCouponInfoByConsumerCouponId(consumerCouponId);
            if (couponInfo == null || couponInfo.Id == 0)
                return null;

            var couponDto = new CouponDto
            {
                CouponInfo = couponInfo,
                CouponBrandLimitList = CouponBrandBLL.Instance.GetListByCouponIds(couponInfo.Id.ToString()),
                CouponCommodityLibLimitList =
                    CouponCommodityLibDAL.Instance.GetListByCouponIds(couponInfo.Id.ToString()),
                CouponCommodityCategoryLimitList =
                    CouponCommodityCategoryDAL.Instance.GetListByCouponIds(couponInfo.Id.ToString())
            };

            return couponDto;
        }

        /// <summary>
        /// 获取用户优惠券信息
        /// </summary>
        /// <param name="consumerCouponIds">消费者优惠券ID集合</param>
        /// <returns></returns>
        public List<CouponDto> BatchGetCouponInfoByConsumerCouponIds(string consumerCouponIds)
        {
            var lsCoupon = CouponDAL.Instance.BatchGetCouponInfoByConsumerCouponIds(consumerCouponIds);
            if (lsCoupon == null || lsCoupon.Count == 0)
                return null;

            return (from coupon in lsCoupon
                where coupon != null && coupon.Id != 0
                select new CouponDto
                {
                    CouponInfo = coupon,
                    CouponBrandLimitList = CouponBrandBLL.Instance.GetListByCouponIds(coupon.Id.ToString()),
                    CouponCommodityLibLimitList =
                        CouponCommodityLibDAL.Instance.GetListByCouponIds(coupon.Id.ToString()),
                    CouponCommodityCategoryLimitList =
                        CouponCommodityCategoryDAL.Instance.GetListByCouponIds(coupon.Id.ToString())
                }).ToList();
        }

        /// <summary>
        /// 获得排除制定类别数据列表
        /// </summary>
        public List<Coupon> GetListExceptSingleCategoryCode(string[] arrCategoryCode)
        {
            var strCategoryCode = string.Empty;
            if (arrCategoryCode != null && arrCategoryCode.Length > 0)
            {
                strCategoryCode = string.Join("','", arrCategoryCode);
                strCategoryCode = "'" + strCategoryCode + "'";
            }

            return CouponDAL.Instance.GetListExceptSingleCategoryCode(strCategoryCode);
        }

        /// <summary>
        /// 根据条件获取优惠券总数
        /// </summary>
        /// <remarks>2016-08-22 万乐园 创建</remarks>
        public int GetTotalCount(string strWhere = null)
        {
            return CouponDAL.Instance.GetTotalCount(strWhere);
        }

        public List<Coupon> GetListByCouponName(string couponName)
        {
            var ds = CouponDAL.Instance.GetListByCouponName(couponName);
            return ServicesHelper.DataSetToIList<Coupon>(ds).ToList();
        }
        #endregion
    }
}